package com.kk.base.service.home;

import com.kk.base.bean.PageBean;
import com.kk.base.dao.admin.BuyOffDao;
import com.kk.base.dao.home.ExpressMailOrderDao;
import com.kk.base.entity.admin.BuyOff;
import com.kk.base.entity.admin.User;
import com.kk.base.entity.common.ExpressMailOrderStatus;
import com.kk.base.entity.home.ExpressMailOrder;
import com.kk.base.entity.home.HomeUser;
import com.kk.base.util.SendEmailUtil;
import com.kk.base.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ExpressMailOrderService {

    @Autowired
    private ExpressMailOrderDao expressMailOrderDao;

    @Autowired
    private BuyOffDao buyOffDao;

    @Value("${email.address}")
    private String sourceEmail; //发件人邮箱

    @Value("${email.authorization-code}")
    private String authorizationCode; //授权码


    /**
     * 分页按订单编号搜索订单列表
     *
     * @param expressMailOrder
     * @param pageBean
     * @return
     */
    public PageBean<ExpressMailOrder> findAllByWaybillNumber(ExpressMailOrder expressMailOrder,
                                                             PageBean<ExpressMailOrder> pageBean) {

        Specification<ExpressMailOrder> specification = (Specification<ExpressMailOrder>) (root, criteriaQuery, criteriaBuilder) -> {

            List<Predicate> predicates = new ArrayList<>();

            predicates.add(criteriaBuilder.equal(root.get("orderStatus"), ExpressMailOrderStatus.HAVEORDER));

            User loginedUser = SessionUtil.getLoginedUser();

            predicates.add(criteriaBuilder.equal(root.get("sendFullAddress"), loginedUser.getAddress()));

            if (null != expressMailOrder) {
                predicates.add(criteriaBuilder.like(root.get("waybillNumber"), "%" + (expressMailOrder.getWaybillNumber() == null ? "" : expressMailOrder.getWaybillNumber()) + "%"));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<ExpressMailOrder> findAll = expressMailOrderDao.findAll(specification, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public ExpressMailOrder find(Long id) {
        return expressMailOrderDao.find(id);
    }

    /**
     * 保存/编辑
     *
     * @param expressMailOrder
     * @return
     */
    public ExpressMailOrder save(ExpressMailOrder expressMailOrder) {
        return expressMailOrderDao.save(expressMailOrder);
    }


    /**
     * 分页按订单状态搜索订单列表
     *
     * @param rsolutionId
     * @param pageBean
     * @return
     */
    public PageBean<ExpressMailOrder> selOrderState(PageBean<ExpressMailOrder> pageBean, String rsolutionId, String waybillNumberStr) {
        HomeUser homeUser = SessionUtil.getHomeUser();
        Specification<ExpressMailOrder> specification = (Specification<ExpressMailOrder>) (root, cq, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            List<Predicate> waybillNumberStrOr = new ArrayList<>();


            if ("1".equals(rsolutionId) || "2".equals(rsolutionId) || "3".equals(rsolutionId) || "4".equals(rsolutionId)) {
                predicates.add(cb.equal(root.get("homeUser").get("id"), homeUser.getId()));
            }

            if ("5".equals(rsolutionId) || "6".equals(rsolutionId) || "7".equals(rsolutionId)) {
                predicates.add(cb.equal(root.get("recipientsMobile"), homeUser.getMobile()));
                predicates.add(cb.notEqual(root.get("orderStatus"), ExpressMailOrderStatus.HAVEORDER));
            }

            if ("2".equals(rsolutionId)) {   //查询已下单
                predicates.add(cb.equal(root.get("orderStatus"), ExpressMailOrderStatus.HAVEORDER));
            }

            if ("3".equals(rsolutionId) || "6".equals(rsolutionId)) {   //查询处理中
                predicates.add(cb.notEqual(root.get("orderStatus"), ExpressMailOrderStatus.HAVEORDER));
                predicates.add(cb.notEqual(root.get("orderStatus"), ExpressMailOrderStatus.SIGNFOR));
            }

            if ("4".equals(rsolutionId) || "7".equals(rsolutionId)) {   //查询已完成
                predicates.add(cb.equal(root.get("orderStatus"), ExpressMailOrderStatus.SIGNFOR));
            }


            if (!StringUtils.isEmpty(waybillNumberStr)) {
                String[] waybillNumberArr = waybillNumberStr.split("-");
                Arrays.asList(waybillNumberArr).forEach(item -> waybillNumberStrOr.add(cb.equal(root.get("waybillNumber"), item)));
            }

            Predicate waybillNumberOr = cb.or(waybillNumberStrOr.toArray(new Predicate[waybillNumberStrOr.size()]));
            if (!waybillNumberOr.getExpressions().isEmpty()) {
                predicates.add(waybillNumberOr);
            }

            cq.orderBy(cb.asc(root.get("orderStatus")),cb.desc(root.get("createTime")));


            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<ExpressMailOrder> findAll = expressMailOrderDao.findAll(specification, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }


    /**
     * 全部保存/编辑
     *
     * @param expressMailOrders
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRES_NEW, timeout = 15)
    public Integer saveAll(List<ExpressMailOrder> expressMailOrders) {
        Integer abnormalJudgment = 0;
        try {
            expressMailOrderDao.saveAll(expressMailOrders);
        } catch (Exception e) {
            abnormalJudgment = 1;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return abnormalJudgment;
    }


    /**
     * 确认收货
     *
     * @param expressMailOrdersId
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRES_NEW, timeout = 15)
    public Integer saveExpressMailOrderAndBuyOff(Long expressMailOrdersId) {
        User loginedUser = SessionUtil.getLoginedUser();
        Integer abnormalJudgment = 0;
        try {
            ExpressMailOrder expressMailOrder = expressMailOrderDao.find(expressMailOrdersId);
            expressMailOrder.setOrderStatus(ExpressMailOrderStatus.TO_COMPLETE_THE_GOODS);
            ExpressMailOrder saveExpressMailOrder = expressMailOrderDao.save(expressMailOrder);

            BuyOff buyOff = new BuyOff();
            buyOff.setBuyOffUser(loginedUser);
            buyOff.setBuyOffExpressMailOrder(saveExpressMailOrder);
            buyOff.setStatus(BuyOff.CONFIRMRECEIPT);
            BuyOff saveBuyOff = buyOffDao.save(buyOff);

            SendEmailUtil sendEmailUtil = new SendEmailUtil();
            sendEmailUtil.setSourceEmail(sourceEmail);  //设置发件人
            //sendEmailUtil.setEmail(expressMailOrder.getHomeUser().getEmail()); 设置收件人
            sendEmailUtil.setEmail(expressMailOrder.getSenderEmail()); //设置收件人
            sendEmailUtil.setCode(authorizationCode); //设置授权码
            sendEmailUtil.sendMsg("快递揽收提醒","订单编号为"+ expressMailOrder.getWaybillNumber()+"已被"+
                    saveBuyOff.getBuyOffUser().getUsername()+"网点揽收，即将被发往"+
                    expressMailOrder.getRecipientsFullAddress()+ expressMailOrder.getRecipientsAddress()+
                    "可前往官网查询物流信息，感谢您选择我们为您提供快递服务！"); //发送消息

        } catch (Exception e) {
            abnormalJudgment = 1;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return abnormalJudgment;
    }

    /**
     *
     * @return
     */
    public Long countByOrderStatus(){
        return expressMailOrderDao.countByOrderStatus(ExpressMailOrderStatus.SIGNFOR);
    }

    /**
     * 根据订单号查询
     * @param waybillNumber
     * @return
     */
    public ExpressMailOrder findByWaybillNumber(String waybillNumber){
        return expressMailOrderDao.findByWaybillNumber(waybillNumber);
    }


    /**
     * 根据id删除
     *
     * @param id
     */
    public void deleteById(Long id) {
        expressMailOrderDao.deleteById(id);
    }


    /**
     * 查询今年的各月份的签收订单
     * @return
     */
    public List<Object> orderCountAndMonthByNowYear(){
        return expressMailOrderDao.orderCountAndMonthByNowYear();
    }

}
